package com.lemon.service;

import java.util.Date;
import java.util.List;

import com.lemon.dao.DepartmentDao;
import com.lemon.domain.Department;

public class DepartmentService {

	private DepartmentDao dao = new DepartmentDao();

	public Department get(Long id) {
		return dao.get(id);
	}
	
	public List<Department> listSubDapartment(Long id) {
		return dao.listSubDapartment(id);
	}
	
	public String listToHtml() {
		return listToHtml(listSubDapartment(null));
	}
	
	/**
	 * 生成以层级方式展示部门列表的html字符
	 * @param departments
	 * @return
	 */
	public String listToHtml(List<Department> departments) {
		if (departments == null) {
			return null;
		}
		
		StringBuilder builder = new StringBuilder("<ul class=\"collapsible\" data-collapsible=\"expandable\" style=\"margin: 0px; border: none;\">");
		for (Department d : departments) {
			builder.append("<li>")
				.append("<div class=\"collapsible-header\" department-id=\"")
				.append(d.getId())
				.append("\">")
				.append(d.getName())
				.append("</div>")
				.append("<div class=\"collapsible-body\">")
				.append(listToHtml(d.getSubDepartments()))
				.append("</div>")
				.append("</li>");
		}
		builder.append("</ul>");
		
		return builder.toString();
	}
	
	public List<Department> list() {
		return dao.list();
	}
	
	public Long save(Department d) {
		d.setCreateTime(new Date());
		return dao.save(d);
	}
	
	public int delete(Long id) {
		return dao.delete(id);
	}
	
	public int update(Department d) {
		d.setUpdateTime(new Date());
		return dao.update(d);
	}
}
